﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Kokomo.Mirror.CliMetadata
{
	public static class ExceptionHandling
	{
		public static IList<ExceptionBlock> GetExceptionBlocks(MethodBase method)
		{
			if (method == null) throw new ArgumentNullException("method");

			MethodBody body = method.GetMethodBody();
			return GetExceptionBlocks(body);
		}
		public static IList<ExceptionBlock> GetExceptionBlocks(MethodBody body)
		{
			if (body == null) throw new ArgumentNullException("body");

			IList<ExceptionHandlingClause> clauses = body.ExceptionHandlingClauses;
			List<ExceptionBlock> blocks = new List<ExceptionBlock>();
			foreach (var clause in clauses)
			{
				ExceptionBlock block = blocks
					.Where(b => (b.TryOffset == clause.TryOffset) && (b.TryLength == clause.TryLength))
					.FirstOrDefault();
				if (block == null)
				{
					block = new ExceptionBlock(clause.TryOffset, clause.TryLength);
					blocks.Add(block);
				}

				block.AddHandlerBlock(clause);
			}

			return blocks;
		}
		public static IList<ExceptionBlockMarker> GetExceptionBlockMarkers(MethodBase method)
		{
			if (method == null) throw new ArgumentNullException("method");

			return GetExceptionBlocks(method).SelectMany(b => b.GetMarkers()).ToArray();
		}
		public static IList<ExceptionBlockMarker> GetExceptionBlockMarkers(MethodBody body)
		{
			return GetExceptionBlocks(body).SelectMany(b => b.GetMarkers()).ToArray();
		}
	}
}
